﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace MALRECrewrite.Models
{
    public class AnimeGroup : INotifyPropertyChanged
    {
        Anime _anime;
        AnimeGroup _parent;

        public List<AnimeGroup> Children { get; private set; }

        public bool IsInitiallySelected { get; private set; }

        public string Title { get; private set; }

        bool? _isChecked = false;

        public AnimeGroup(string title, Anime a, AnimeGroup p = null)
        {
            _anime = a;
            Title = title;
            _parent = p;
            Children = new List<AnimeGroup>();

            if(a != null)
                SetIsChecked(a.IsActive, true, true);
        }

        public bool? IsChecked
        {
            get { return _isChecked; }
            set { this.SetIsChecked(value, true, true); if(_anime != null)_anime.IsActive = value.Value; }
        }

        private void SetIsChecked(bool? value, bool updateChildren, bool updateParent)
        {
            if (value == _isChecked)
                return;

            _isChecked = value;

            if (updateChildren && _isChecked.HasValue)
                this.Children.ForEach(c => c.SetIsChecked(_isChecked, true, false));

            if (updateParent && _parent != null)
                _parent.VerifyCheckState();

            this.OnPropertyChanged("IsChecked");
        }

        private void VerifyCheckState()
        {
            bool? state = null;
            for (int i = 0; i < this.Children.Count; ++i)
            {
                bool? current = this.Children[i].IsChecked;
                if (i == 0)
                {
                    state = current;
                }
                else if (state != current)
                {
                    state = null;
                    break;
                }
            }
            this.SetIsChecked(state, false, true);
        }

        #region INotifyPropertyChanged Members

        private void OnPropertyChanged(string prop)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion INotifyPropertyChanged Members
    }
}